package com.example.user

import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.example.lib_base.mvvm.BaseActivity
import com.example.user.databinding.ActivityUserInfoBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

@Route(path = "/user/UserInfoActivity")
class UserInfoActivity : BaseActivity<ActivityUserInfoBinding, UserViewModel>() {
    override fun initView() {
        viewModel.userInfo()
        binding.btnUpdatepwd.setOnClickListener {
            //startActivity(Intent(this,UpdatePwdActivity::class.java))
            ARouter.getInstance().build("/user/UpdatePwdActivity").navigation()
        }
        binding.ivIcon.setOnClickListener {
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }
    }

    override fun initData() {
        viewModel.userInfoSuccess.observe(this) {
            if (it.code == 200) {
                //binding.tvPhone.text = "手机号:${it.data.phone}"
                //使用数据绑定形式展示
                binding.userInfo = it.data
            }
        }
        viewModel.uploadSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong(it.data.url)
                //调用修改用户信息的接口
            }
        }
    }

    override fun getViewModel(): Class<UserViewModel> = UserViewModel::class.java

    override fun getLayout(): Int = R.layout.activity_user_info

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            Glide.with(this).load(pictureBean.path).into(binding.ivIcon)
            //调用接口
            var body = RequestBody.create(
                "multipart/form-data".toMediaTypeOrNull(),
                File(pictureBean.path)
            )
            var part = MultipartBody.Part.createFormData("multipart", "a.png", body)
            viewModel.upload("user", part, "0")
        }
    }

}